package com.googlecode.publicholiday.config;

import com.googlecode.publicholiday.repository.jdbc.Bootstrapper;
import com.googlecode.publicholiday.repository.jdbc.H2JdbcBootstrapper;
import org.h2.jdbcx.JdbcDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@PropertySource(value = "public-holiday.properties")
public class DataSourceConfig {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource() {
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setURL(environment.getProperty("public-holiday.jdbc.connection.url"));
        dataSource.setUser(environment.getProperty("public-holiday.jdbc.connection.username"));
        dataSource.setPassword(environment.getProperty("public-holiday.jdbc.connection.password"));
        return dataSource;
    }

    @Bean(initMethod = "execute")
    public Bootstrapper bootstrapper() {
        return new H2JdbcBootstrapper(dataSource());
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}
